<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :inline="true"
      label-width="80px1"
    >
      <el-form-item prop="queryName">
        <template #label>
          <span style="font-weight: bold">姓名</span>
        </template>
        <el-input v-model="formData.queryName" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item prop="queryIdCard">
        <template #label>
          <span style="font-weight: bold">身份证号</span>
        </template>
        <el-input v-model="formData.queryIdCard" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item v-if="formData.validMethod === 2" prop="queryMobile">
        <template #label>
          <span style="font-weight: bold">手机号</span>
        </template>
        <el-input v-model="formData.queryMobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item prop="validMethod" class="!w-240px">
        <template #label>
          <span style="font-weight: bold">校验方式</span>
        </template>
        <el-select v-model="formData.validMethod">
          <el-option :value="0" label="关闭校验"/>
          <el-option :value="1" label="二要素校验"/>
          <el-option :value="2" label="三要素校验"/>
        </el-select>
      </el-form-item>
      <el-row style="margin-top: 10px" type="flex" class="row-bg" justify="left" align="center" >
        <el-col :span="24">
          <el-form-item prop="queryType" style="margin-bottom: 0">
            <template #label>
              <span style="font-weight: bold">类型</span>
            </template>
            <el-checkbox @change="handleCheckAllChange">全选</el-checkbox>
            <el-checkbox @change="handleCheckNormalChange">默认类型</el-checkbox>
            <Icon icon="ep:edit" @click="handleCheckNormalChangeIcon" class="ml-5px" style="cursor: pointer" color="blue" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="  " prop="qqq">
            <div></div>
            <el-checkbox-group v-model="formData.queryType">
              <el-checkbox v-for="api in dataApis" :key="api.id" :value="api.code" :label="api.name + ' ( ' + api.price + ' 元 )'"/>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px" type="flex" class="row-bg" justify="center" align="center" >
        <el-button @click="queryReport" type="primary">查询报告</el-button>
      </el-row>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="查询姓名" prop="queryName">
        <el-input
          v-model="queryParams.queryName"
          placeholder="请输入查询姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
      <el-table-column
        type="index"
        width="50"/>
      <el-table-column label="姓名" width="70" align="center" prop="queryName" />
      <el-table-column label="身份证号" width="190" align="center" prop="queryIdCard" />
      <el-table-column label="查询类型" align="left" prop="queryType">
        <template #default="{row}">
          <el-tag class="mr-5px" v-for="(type, idx) in row.queryType" :key="idx">{{allApis.find(t => t.code === type).name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="授权书" width="130" align="center" prop="sqs">
        <template #default="{row}">
          <el-button type="text" @click="showSqs(row.queryName, row.queryIdCard, row.queryTime)">个人信息授权书</el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="查询时间"
        align="center"
        prop="queryTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="showDetail(scope.row.id)"
            v-hasPermi="['business:data-query:update']"
          >
            查看
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['business:data-query:delete']"
          >
            删除
          </el-button>
          <el-button
            v-if="scope.row.auditIsBlacklist === false"
            link
            type="primary"
            @click="addBlackList(scope.row.id)"
            v-hasPermi="['business:data-query:create']"
          >
            加入黑名单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <Dialog title="个人信息授权书" v-model="sqsShow" center>
    <div>
      <p>本人姓名：{{ name }}</p><br/>
      <p>身份证号：{{ idCard }}</p><br/>
      <p>因本人申请<strong>融资担保</strong>业务所需，故向贵公司作出以下授权：</p><br/>
      <p><strong>一、本人经充分了解相关法律法规，同意授权贵公司通过第三方机构（包括但不限于 朴道征信有限公司等征信机构）或指定第三方收集本人的个人信息（包括但不限于本人公民身份信息、联系方式、个人征信记录等），授权期至本人业务结清之日止，本人同意所收集的本人信息可用于个人办理业务申请、对已发放的业务进行业务前后风险管理及风险评估与控制。</strong></p><br/>
      <p><strong>二、本人同意朴道征信有限公司（联系方式：service@pudaocredit.cn ）基于为本人与贵公司之间的金融活动提供信用服务的目的，可向贵公司和有关部门、单位（包括但不限于公安、司法、教育、全国公民身份证号码查询服务中心、通信运营商、银联、通联、易宝、宝付、社保、公积金、税务、民政、物流、电子商务平台、互联网平台、行业协会等合法留存本人信息的第三方机构等）查询、核实、采集、整理、保存、加工本人能够用于判断个人信用状况的各类信息（包括但不限于个人的身份、地址、交通、通信、债务、财产、支付、消费、生产经营、履行法定义务等信息，以及基于前述信息对个人信用状况形成的分析、评价类信息），包括可能对本人产生负面影响的不良信息，并可将上述信息在本授权书所列的用途范围内向贵公司提供。上述信息的保存期限为法律法规要求的最短时间，其中个人不良信息的保存期限为自不良行为或事件终止之日起5年。</strong></p><br/>
      <p><strong>三、本人同意授权合法存有本人信息的机构向第三方机构（包括但不限于征信机构）提供本人的上述信息。</strong></p><br/>
      <p>特别声明：<strong>本人已知悉本授权书全部内容（特别是加粗字体内容）的含义及因此产生的法律效力，自愿做出以上授权。本授权书是本人真实意思表示，本人同意承担由此带来的一切法律后果。</strong></p><br/>
      <p>特别提示：本授权书效力具有独立性，不因相关业务合同或条款无效或被撤销而无效或失效，<strong>本授权一经作出，便不可撤销</strong>。为了保障您的合法权益，您应当阅读并遵守本授权书。请您务必审慎阅读，并充分理解本授权书的全部内容，特别是以加粗形式提示您注意的。<strong>若您不接受本授权书的任何条款，请您立即停止授权。</strong></p><br/>
      <p>授权人：{{ name }}</p><br/>
      <p>授权日期：{{ queryTime0 ? formatDate(queryTime0, 'YYYY-MM-DD') : '' }}</p>
    </div>
  </Dialog>

  <Dialog title="授权提示" v-model="sqTipShow" center>
    <div>
      <p>您点击 “确定授权”，即表示您已阅读并同意：
        <el-button type="text" style="color: #faad14" @click="showSqs(formData.queryName, formData.queryIdCard, '')">《个人信息授权书》</el-button>
      </p>
    </div>
    <template #footer>
      <el-button @click="submitForm" :disabled="submitFormDis" type="primary">确认授权</el-button>
      <el-button @click="sqTipShow = false">取 消</el-button>
    </template>
  </Dialog>

  <Dialog title="默认类型" v-model="normalTypeShow" center>
    <el-checkbox-group v-model="userNormalData">
      <el-checkbox v-for="api in dataApis" :key="api.id" :value="api.code" :label="api.name"/>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="normalTypeSave" type="primary">保 存</el-button>
      <el-button @click="normalTypeShow = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import {dateFormatter, dateFormatter2, formatDate} from '@/utils/formatTime'
import { DataQueryApi, DataQuery } from '@/api/business/dataquery'
import {ContentWrap} from "@/components/ContentWrap";
import {ApiTypeInfoApi} from "@/api/business/apitypeinfo";
import { BizConfigApi, BizConfig } from '@/api/business/config'
import { DataQueryNomralTypeApi } from '@/api/business/dataquerynomraltype'
import {Icon} from "@/components/Icon";

/** 数据查询 列表 */
defineOptions({ name: 'DataQuery' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<DataQuery[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  deptId: undefined,
  queryName: undefined,
  queryIdCard: undefined,
  queryMobile: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const route = useRoute() // 路由
const router = useRouter() // 路由

/** 查详情 */
const showDetail = async (id:number) => {
  router.push({
    name: 'DataQueryDetail',
    query: { id, location: 'DataQuery' }
  })
}
const dataApis = ref()
/** 查询列表 */
const getDataApis = async () => {
  dataApis.value = await ApiTypeInfoApi.getApiTypeInfoAll(1)
}
/** 查询列表 */
const handleCheckAllChange = async (flag) => {
  formData.value.queryType = flag ? dataApis.value.map(api => api.code) : []
}


/** 默认类型 */
let normalTypeShow = ref(false);
let userNormalData = ref([]);
const handleCheckNormalChangeIcon = async (flag) => {
  normalTypeShow.value = true
}
const normalTypeSave = async () => {
  await DataQueryNomralTypeApi.createDataQueryNomralType({typeCode: userNormalData.value})
  message.success("保存成功")
  normalTypeShow.value = false
}
const initNormalType = async () => {
  userNormalData.value = await DataQueryNomralTypeApi.getDataQueryNomralType()
}
const handleCheckNormalChange = async (flag) => {
  formData.value.queryType = flag ? userNormalData.value : []
}


/** 加入黑名单 */
const addBlackList = async (id:number) => {
  let remark = await message.promptCustom("确认加入黑名单吗？", "提示")
  await DataQueryApi.addBlacklist(id, remark.value)
  message.success(t('common.success'))
  getList()
}

// 查询授权书
let sqsShow = ref(false);
let name = ref();
let idCard = ref();
let queryTime0 = ref();
const showSqs = async (queryName, queryIdCard, queryTime) => {
  name.value = queryName;
  idCard.value = queryIdCard;
  if (queryTime){
    queryTime0.value = queryTime;
  }else {
    queryTime0.value = Date.now();
  }
  sqsShow.value = true;
}


const allApis = ref()
/** 查询列表 */
const getAllApis = async () => {
  allApis.value = await ApiTypeInfoApi.getApiTypeInfoAll('')
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DataQueryApi.getDataQueryPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DataQueryApi.deleteDataQuery(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: DataQuery[]) => {
  checkedIds.value = records.map((item) => item.id);
}

// 获取默认手机号
const getNormalMobile = async () => {
  formData.value.queryMobile = (await BizConfigApi.getBizConfig(1)).value
}

let sqTipShow = ref(false)
const queryReport = async () => {
  // 校验表单
  await formRef.value.validate()

  sqTipShow.value = true
}

let submitFormDis = ref(false);

const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 提交请求
  try {
    submitFormDis.value = true;
    const data = formData.value as unknown as DataQuery
    let id = await DataQueryApi.createDataQuery(data)
    resetForm();
    message.success("查询成功")

    router.push({
      name: 'DataQueryDetail',
      query: { id, location: 'DataQuery' }
    })
  } finally {
    submitFormDis.value = false;
  }
}

const formData = ref({
  validMethod: undefined,
  queryName: undefined,
  queryIdCard: undefined,
  queryMobile: undefined,
  queryType: [],
})
const formRules = reactive({
  validMethod: [{ required: true, message: '校验方式不能为空', trigger: 'blur' }],
  queryName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  queryIdCard: [{ required: true, message: '身份证号不能为空', trigger: 'blur' }],
  queryMobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
  queryType: [{ required: true, message: '查询类型不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    validMethod: undefined,
    queryName: undefined,
    queryIdCard: undefined,
    queryMobile: undefined,
    queryType: [],
  }
  formRef.value?.resetFields()
}

/** 初始化 **/
onMounted(() => {
  getAllApis()
  getList()
  getDataApis()
  getNormalMobile()
  initNormalType()
  formData.value.validMethod = 1
})
</script>
